﻿using System;
using System.Windows.Forms;
using System.Net;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using DX_Recognize.Entitys;
using DX_Recognize.Common;
using static DX_Recognize.Utils.ConvertUtils;
using ZwSoft.ZwCAD.EditorInput;
using ZwSoft.ZwCAD.ApplicationServices;
using ZwSoft.ZwCAD.DatabaseServices;
using System.Threading.Tasks;
using System.IO;
using System.Linq;
using System.ComponentModel;
using System.Drawing.Drawing2D;
using System.Security.Policy;
using System.IO.Pipes;
using System.Security.Cryptography;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel;
using DX_Recognize.Disposition;
using DX_Recognize.AuxiliaryTool;
using Newtonsoft.Json.Serialization;
using System.Reflection;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;

namespace DX_Recognize.Utils
{
    public class HttpUtils
    {
        private const int MaxRetries = 3;
        private const int RetryDelaySeconds = 2;

        private static string FILESYSURL = "http://dxmslc.gddxmg.com:8082/";
        private static string FILESYSHoleURL = "prod-api/mes/mo/holdPosition/getPosition";
        private static string FILESYSQuaURL = "prod-api/mes/ct/qaotation/getQaotationDetailByCode";
        public event Action ChangePageControlSelectIndexAction;
        
        public HttpUtils()
        {

        }

        public async Task<string> ERPPartyReqEvent(string jsonContent, ConvertUtils CU, AMTypeUPloadRecordInfo RInfo)
        {
            try
            {
                string apiUrl = "http://116.205.238.176:82/dxquoapi1/mes/importMouldData";
                int retryCount = 0;
                string errorMessage = null;
                while (retryCount < MaxRetries)
                {
                    HttpClient httpClient = new HttpClient();
                    httpClient.Timeout = TimeSpan.FromSeconds(1500);
                    using (var content = new StringContent(jsonContent, Encoding.UTF8, "application/json"))
                    {
                        HttpResponseMessage response = await httpClient.PostAsync(apiUrl, content);
                        if (response.StatusCode == HttpStatusCode.OK)
                        {
                            var jsonResponse = await response.Content.ReadAsStringAsync();
                            JObject jsonParseObj = JObject.Parse(jsonResponse);
                            string resStr = jsonParseObj.ToString();
                            string mesStr = jsonParseObj["data"].ToString();
                            Boolean successF = jsonParseObj["code"].ToString().Equals("0");
                            if (successF)
                            {
                                //Save YploadRecord -> DB
                                Mould.SaveUploadRecordToDB(RInfo, RInfo.jobNumberName);
                                CUException invokeSuccess = new CUException(ErrorType.ERPInvokeSuccess);
                                CU.CallERPLog(true, invokeSuccess, mesStr, RInfo);
                                MessageBox.Show(UserPromptType.AMUploadToErp);
                                return await response.Content.ReadAsStringAsync();
                            }
                            else
                            {
                                //保存到中途记录 接单进行2次更改后再上传
                                CUException invokeSuccess = new CUException(ErrorType.ERPInteriorError);
                                CU.CallERPLog(false, invokeSuccess, mesStr, RInfo);
                                StringBuilder builder = new StringBuilder();
                                string errorQstr = "问题点: " + mesStr + "\n";
                                errorQstr += "已保存至中途记录,请按指示更改数据!";
                                MessageBox.Show(errorQstr);
                                if (RInfo.uploadType == 1)
                                    RInfo.uploadType = 3;
                                if (RInfo.uploadType == 2)
                                    RInfo.uploadType = 4;
                                //Record
                                Mould.SaveUploadRecordToDB(RInfo, RInfo.jobNumberName);
                                //Skip Page
                                ChangePageControlSelectIndexAction?.Invoke();
                                return await response.Content.ReadAsStringAsync();
                            }
                        }
                        else
                        {
                            Boolean F = retryCount + 1 == MaxRetries;
                            if (F)
                            {
                                CUException invokeSuccess = new CUException(ErrorType.ERPHttpStatusError);
                                CU.CallERPLog(false, invokeSuccess, invokeSuccess.Message, RInfo);
                                MessageBox.Show(invokeSuccess.ErrorTig());
                                return await response.Content.ReadAsStringAsync();
                            }
                        }
                    }
                    retryCount++;
                    if (retryCount < MaxRetries)
                        await Task.Delay(RetryDelaySeconds * 1000);
                }
                MessageBox.Show(UserPromptType.MaxTimeUploadFailTig);
                int uploadType = RInfo.uploadType;
                if (uploadType == 1)
                    RInfo.uploadType = 3;
                if (uploadType == 2)
                    RInfo.uploadType = 4;
                //Record
                Mould.SaveUploadRecordToDB(RInfo, RInfo.jobNumberName);
                //Timeout Error 
                CUException timeError = new CUException(ErrorType.ERPTimeout);
                string qstr = timeError.ErrorTig();
                qstr += "已保存至中途记录,请稍后重试上传!";
                MessageBox.Show(qstr);
                CU.CallERPLog(false, timeError, errorMessage, RInfo);
                //Skip Page
                ChangePageControlSelectIndexAction?.Invoke();
                //throw new Exception("All attempts failed to call ERP API.");
            }
            catch (Exception ex)
            {
                string errorMessage = ex.Message;
                CUException invokeError = new CUException(ErrorType.BeforeInvokeERPError);
                CU.CallERPLog(false, invokeError, errorMessage, RInfo);
                MessageBox.Show(invokeError.ErrorTig());
            }
            throw new Exception("All attempts failed to call ERP API.");
        }

        //RP Length Check Rule
        
        public AMTypeCheckWarn CheckRPLengthRule()
        {
            AMTypeCheckWarn Res = new AMTypeCheckWarn();
            int rpIndex = ShareItemData.ItemList.FindIndex(item => item.ItemCode.Equals("ReturnPin"));
            if (rpIndex != -1)
            {
                double tomCompareH = ShareItemData.ItemList[rpIndex].TheoryH;
                int fIndex = AssemblyShareData.ASectionList.FindIndex(item => item.BoardCode.Equals("fangtie"));
                if(fIndex != -1)
                {
                    double fThick = AssemblyShareData.ASectionList[fIndex].PlateThick;
                    int beforefIndex = fIndex - 1;
                    if(beforefIndex >= 0)
                    {
                        double beforeFThick = AssemblyShareData.ASectionList[beforefIndex].PlateThick;
                        List<BoardSectionItem> epfpBList =  AssemblyShareData.ASectionList.FindAll(item => item.BoardCode.Equals("epBoard")
                        || item.BoardCode.Equals("fpBoard")).ToList();
                        if(epfpBList.Count > 0)
                        {
                            double allepfpBThick = 0;
                            epfpBList.ForEach(item => allepfpBThick += item.PlateThick);
                            BoardSectionItem firstepfpB = epfpBList.First();
                            double estimateBThick = beforeFThick + fThick - allepfpBThick + firstepfpB.PlateThick;
                            estimateBThick = ComputedUtils.RPTheoryLRepRule(estimateBThick);
                            if(tomCompareH != estimateBThick)
                            {
                                Res.warnF = false;
                                Res.tig = "回针推荐长度为: " + estimateBThick + " 识别长度为: " + tomCompareH + " 请确认!";
                            }
                        }
                    }
                }
            }
            return Res;
        }

        public AMTypeCheckWarn ATypeRItemWithDBFoolPro()
        {
            AMTypeCheckWarn Res = new AMTypeCheckWarn();
            Boolean UIF = false;
            StringBuilder UIsb = new StringBuilder();
            List<BoardSectionItem> FBList = AssemblyShareData.AUIBlueSectionList.FindAll(item => item.BoardCode.Equals("fangtie"));
            //Fangtie Width
            int epBIndex = AssemblyShareData.AUIBlueSectionList.FindIndex(item => item.BoardCode.Equals("epBoard"));
            int fpBIndex = AssemblyShareData.AUIBlueSectionList.FindIndex(item => item.BoardCode.Equals("fpBoard"));
            if (epBIndex != -1 || fpBIndex != -1)
            {
                double pw = 0;
                if (epBIndex != -1)
                    pw = AssemblyShareData.AUIBlueSectionList[epBIndex].PlateWidth;
                else
                if (fpBIndex != -1)
                    pw = AssemblyShareData.AUIBlueSectionList[fpBIndex].PlateWidth;
                if (FBList.Count > 0)
                {
                    int fIndex = FBList.FindIndex(item => item.Num == 2);
                    if (fIndex != -1)
                    {
                        double ft = FBList[fIndex].PlateWidth;
                        double refW = 0;
                        int aBIndex = AssemblyShareData.AUIBlueSectionList.FindIndex(item => item.BoardCode.Equals("aBoard"));
                        if (aBIndex != -1)
                            refW = AssemblyShareData.AUIBlueSectionList[aBIndex].PlateWidth;
                        Boolean WF = refW - pw - ft * 2 >= 0;
                        if (!WF)
                        {
                            Res.warnF = false;
                            UIsb.AppendLine("方铁宽度有误 请核对!");
                        }
                    }
                }
            }

            AMTypeCheckWarn checkRPL = CheckRPLengthRule();
            if (!checkRPL.warnF)
            {
                UIF = true;
                Res.warnF = false;
                UIsb.AppendLine(checkRPL.tig);
            }

            string NowMoldSize = ComputedUtils.ATypeGetMoldSizeFormat();
            int nearSize = ComputedUtils.GetMNearMoldSize(NowMoldSize);
            string CommonMouldSeries = "通用";
            string MouldSeries = null;
            if (CADCommonForm.MoldTypeStr.Equals("PP"))
                MouldSeries = "细水口";
            if (CADCommonForm.MoldTypeStr.Equals("SG"))
                MouldSeries = "大水口";
            if (CADCommonForm.MoldTypeStr.Equals("TP"))
                MouldSeries = "简化型";
            List<StandardHoleData> DBSHList = ParamsConfigData.MoldHoleList.FindAll(item =>
             item.MouldSize == nearSize &&
             (item.MouldSeries.Equals(CommonMouldSeries) || item.MouldSeries.Equals(MouldSeries)));

            if(DBSHList.Count > 0)
            {
                int smallSNum = DBSHList.FindAll(item => item.Item.Equals("小螺丝")).Count;
                int bigSNum = DBSHList.FindAll(item => item.Item.Equals("大螺丝")).Count;
                int epfpSNum = DBSHList.FindAll(item => item.Item.Equals("针板螺丝")).Count;
                int rpSNum = DBSHList.FindAll(item => item.Item.Equals("回针")).Count;
                int spSNum = DBSHList.FindAll(item => item.Item.Equals("拉杆")).Count;
                int gpSNum = DBSHList.FindAll(item => item.Item.Equals("导柱")).Count;

                List<SingleItem> ItemList = ShareItemData.UIItemList;

                int gpIndex = ItemList.FindIndex(item => item.ItemNameType == DItemNameType.GuidePin);
                if (gpIndex != -1)
                {
                    int checkNum = (int)ItemList[gpIndex].ItemNum;
                    Boolean singleF = checkNum % 2 == 1;
                    if (singleF)
                    {
                        Res.warnF = false;
                        string tempTig = "导柱数量不为单数请核对!";
                        UIsb.AppendLine(tempTig);
                    }
                    else
                    {
                        UIF = checkNum < gpSNum;
                        if (UIF)
                        {
                            Res.warnF = false;
                            string tempTig = "导柱数量少于标准(" + gpSNum + "个)请核对!";
                            UIsb.AppendLine(tempTig);
                        }
                    }
                    
                }

                int spIndex = ItemList.FindIndex(item => item.ItemNameType == DItemNameType.SupportPin
                || item.ItemNameType == DItemNameType.NoNozzleMesonSupportPin);
                if (spIndex != -1)
                {
                    int checkNum = (int)ItemList[spIndex].ItemNum;
                    string ItemName = ItemList[spIndex].ItemName;
                    Boolean singleF = checkNum % 2 == 1;
                    if (singleF)
                    {
                        Res.warnF = false;
                        string tempTig = ItemName + "数量不为单数请核对!";
                        UIsb.AppendLine(tempTig);
                    }
                    else
                    {
                        UIF = checkNum < spSNum;
                        if (UIF)
                        {
                            Res.warnF = false;
                            string tempTig = ItemName + "数量少于标准(" + spSNum + "个)请核对!";
                            UIsb.AppendLine(tempTig);
                        }
                    }
                }

                int rpIndex = ItemList.FindIndex(item => item.ItemNameType == DItemNameType.ReturnPin);
                if (rpIndex != -1)
                {
                    int checkNum = (int)ItemList[rpIndex].ItemNum;
                    Boolean singleF = checkNum % 2 == 1;
                    if (singleF)
                    {
                        Res.warnF = false;
                        string tempTig = "回针数量不为单数请核对!";
                        UIsb.AppendLine(tempTig);
                    }
                    else
                    {
                        UIF = checkNum < rpSNum;
                        if (UIF)
                        {
                            Res.warnF = false;
                            string tempTig = "回针数量少于标准(" + rpSNum + "个)请核对!";
                            UIsb.AppendLine(tempTig);
                        }
                    }
                }

                int tpIndex = ItemList.FindIndex(item => item.ItemNameType == DItemNameType.TopPanelScrew);
                if (tpIndex != -1)
                {
                    int checkNum = (int)ItemList[tpIndex].ItemNum;
                    Boolean singleF = checkNum % 2 == 1;
                    if (singleF)
                    {
                        Res.warnF = false;
                        string tempTig = "面板螺丝数量不为单数请核对!";
                        UIsb.AppendLine(tempTig);
                    }
                    else
                    {
                        UIF = checkNum < bigSNum;
                        if (UIF)
                        {
                            Res.warnF = false;
                            string tempTig = "面板螺丝数量少于标准(" + bigSNum + "个)请核对!";
                            UIsb.AppendLine(tempTig);
                        }
                    }
                }

                int kIndex = ItemList.FindIndex(item => item.ItemNameType == DItemNameType.GenericScrew);
                if (kIndex != -1)
                {
                    int checkNum = (int)ItemList[kIndex].ItemNum;
                    Boolean singleF = checkNum % 2 == 1;
                    if (singleF)
                    {
                        Res.warnF = false;
                        string tempTig = "公制螺丝数量不为单数请核对!";
                        UIsb.AppendLine(tempTig);
                    }
                    else
                    {
                        UIF = checkNum < bigSNum;
                        if (UIF)
                        {
                            Res.warnF = false;
                            string tempTig = "公制螺丝数量少于标准(" + bigSNum + "个)请核对!";
                            UIsb.AppendLine(tempTig);
                        }
                    }
                }

                int fIndex = ItemList.FindIndex(item => item.ItemNameType == DItemNameType.SpaceBlockScrew);
                if (fIndex != -1)
                {
                    int checkNum = (int)ItemList[fIndex].ItemNum;
                    Boolean singleF = checkNum % 2 == 1;
                    if (singleF)
                    {
                        Res.warnF = false;
                        string tempTig = "方铁螺丝数量不为单数请核对!";
                        UIsb.AppendLine(tempTig);
                    }
                    else
                    {
                        UIF = checkNum < bigSNum;
                        if (UIF)
                        {
                            Res.warnF = false;
                            string tempTig = "方铁螺丝数量少于标准(" + bigSNum + "个)请核对!";
                            UIsb.AppendLine(tempTig);
                        }
                    }
                }

                int bpIndex = ItemList.FindIndex(item => item.ItemNameType == DItemNameType.BottomPanelScrew);
                if (bpIndex != -1)
                {
                    int checkNum = (int)ItemList[bpIndex].ItemNum;
                    Boolean singleF = checkNum % 2 == 1;
                    if (singleF)
                    {
                        Res.warnF = false;
                        string tempTig = "底板螺丝数量不为单数请核对!";
                        UIsb.AppendLine(tempTig);
                    }
                    else
                    {
                        UIF = checkNum < smallSNum;
                        if (UIF)
                        {
                            Res.warnF = false;
                            string tempTig = "底板螺丝数量少于标准(" + smallSNum + "个)请核对!";
                            UIsb.AppendLine(tempTig);
                        }
                    }
                }

                int epfpIndex = ItemList.FindIndex(item => item.ItemNameType == DItemNameType.PinBoardScrew);
                if (epfpIndex != -1)
                {
                    int checkNum = (int)ItemList[epfpIndex].ItemNum;
                    Boolean singleF = checkNum % 2 == 1;
                    if (singleF)
                    {
                        Res.warnF = false;
                        string tempTig = "针板螺丝数量不为单数请核对!";
                        UIsb.AppendLine(tempTig);
                    }
                    else
                    {
                        UIF = checkNum < epfpSNum;
                        if (UIF)
                        {
                            Res.warnF = false;
                            string tempTig = "针板螺丝数量少于标准(" + epfpSNum + "个)请核对!";
                            UIsb.AppendLine(tempTig);
                        }
                    }
                }
            }
            Res.tig = UIsb.ToString();
            return Res;
        }

        //DB SurItem Fool-Proofing(Num)
        public AMTypeCheckWarn ATypeSurItemWithDBFoolPro()
        {
            AMTypeCheckWarn warnInfo = new AMTypeCheckWarn();
            Boolean SurF = false;
            StringBuilder Sursb = new StringBuilder();
            string NowMoldSize = ComputedUtils.ATypeGetMoldSizeFormat();
            int nearSize = ComputedUtils.GetMNearMoldSize(NowMoldSize);
            string CommonMouldSeries = "通用";
            string MouldSeries = null;
            if (CADCommonForm.MoldTypeStr.Equals("PP"))
                MouldSeries = "细水口";
            if (CADCommonForm.MoldTypeStr.Equals("SG"))
                MouldSeries = "大水口";
            if (CADCommonForm.MoldTypeStr.Equals("TP"))
                MouldSeries = "简化型";
            List<StandardHoleData> DBSHList = ParamsConfigData.MoldHoleList.FindAll(item =>
             item.MouldSize == nearSize &&
             (item.MouldSeries.Equals(CommonMouldSeries) || item.MouldSeries.Equals(MouldSeries)));

            if (DBSHList.Count > 0)
            {
                int smallSNum = DBSHList.FindAll(item => item.Item.Equals("小螺丝")).Count;
                int bigSNum = DBSHList.FindAll(item => item.Item.Equals("大螺丝")).Count;
                int epfpSNum = DBSHList.FindAll(item => item.Item.Equals("针板螺丝")).Count;
                int rpSNum = DBSHList.FindAll(item => item.Item.Equals("回针")).Count;
                int spSNum = DBSHList.FindAll(item => item.Item.Equals("拉杆")).Count;
                int gpSNum = DBSHList.FindAll(item => item.Item.Equals("导柱")).Count;
                List<LabourSingleItem> ItemList = ShareItemData.UISurplusItemList;

                //Process Bush
                if(ItemList.Count > 0)
                {
                    List<LabourSingleItem> aboutBushList = ShareItemData.UISurplusItemList.FindAll(item => item.ItemName.Contains("套"));
                    if(aboutBushList.Count > 0)
                    {
                        for(int i = 0; i < aboutBushList.Count; i++)
                        {
                            LabourSingleItem bushItem = aboutBushList[i];
                            Boolean GPbushF = bushItem.ItemName.Contains("导柱");
                            Boolean SPbushF = bushItem.ItemName.Contains("拉杆");
                            if (GPbushF)
                            {
                                int checkNum = bushItem.ItemNum;
                                Boolean singleF = checkNum % 2 == 1;
                                if (singleF)
                                {
                                    warnInfo.warnF = false;
                                    string tempTig = bushItem.ItemName + "数量不为单数请核对!";
                                    Sursb.AppendLine(tempTig);
                                }
                                else
                                {
                                    SurF = checkNum < gpSNum;
                                    if (SurF)
                                    {
                                        warnInfo.warnF = false;
                                        string tempTig = bushItem.ItemName + "数量少于标准(" + gpSNum + "个)请核对!";
                                        Sursb.AppendLine(tempTig);
                                    }
                                }
                            }
                            if (SPbushF)
                            {
                                int checkNum = bushItem.ItemNum;
                                Boolean singleF = checkNum % 2 == 1;
                                if (singleF)
                                {
                                    warnInfo.warnF = false;
                                    string tempTig = bushItem.ItemName + "数量不为单数请核对!";
                                    Sursb.AppendLine(tempTig);
                                }
                                else
                                {
                                    SurF = bushItem.ItemNum < spSNum;
                                    if (SurF)
                                    {
                                        warnInfo.warnF = false;
                                        string tempTig = bushItem.ItemName + "数量少于标准(" + spSNum + "个)请核对!";
                                        Sursb.AppendLine(tempTig);
                                    }
                                }
                            }
                        }
                    }
                }
                

                int gpIndex = ItemList.FindIndex(item => item.ItemName.Equals("导柱"));
                if (gpIndex != -1)
                {
                    int checkNum = ItemList[gpIndex].ItemNum;
                    Boolean singleF = checkNum % 2 == 1;
                    if (singleF)
                    {
                        warnInfo.warnF = false;
                        string tempTig = "导柱数量不为单数请核对!";
                        Sursb.AppendLine(tempTig);
                    }
                    else
                    {
                        SurF = checkNum < gpSNum;
                        if (SurF)
                        {
                            warnInfo.warnF = false;
                            string tempTig = "导柱数量少于标准(" + gpSNum + "个)请核对!";
                            Sursb.AppendLine(tempTig);
                        }
                    }
                }

                int spIndex = ItemList.FindIndex(item => item.ItemName.Equals("拉杆")
                || item.ItemNameType == DItemNameType.NoNozzleMesonSupportPin);
                if (spIndex != -1)
                {
                    int checkNum = ItemList[spIndex].ItemNum;
                    Boolean singleF = checkNum % 2 == 1;
                    if (singleF)
                    {
                        warnInfo.warnF = false;
                        string tempTig = "拉杆数量不为单数请核对!";
                        Sursb.AppendLine(tempTig);
                    }
                    else
                    {
                        SurF = checkNum < spSNum;
                        if (SurF)
                        {
                            warnInfo.warnF = false;
                            string tempTig = "拉杆数量少于标准(" + spSNum + "个)请核对!";
                            Sursb.AppendLine(tempTig);
                        }
                    }

                }

                int rpIndex = ItemList.FindIndex(item => item.ItemName.Equals("回针"));
                if (rpIndex != -1)
                {

                    int checkNum = ItemList[rpIndex].ItemNum;
                    Boolean singleF = checkNum % 2 == 1;
                    if (singleF)
                    {
                        warnInfo.warnF = false;
                        string tempTig = "回针数量不为单数请核对!";
                        Sursb.AppendLine(tempTig);
                    }
                    else
                    {
                        SurF = checkNum < rpSNum;
                        if (SurF)
                        {
                            warnInfo.warnF = false;
                            string tempTig = "回针数量少于标准(" + rpSNum + "个)请核对!";
                            Sursb.AppendLine(tempTig);
                        }
                    }

                }

                int tpIndex = ItemList.FindIndex(item => item.ItemName.Equals("面板螺丝"));
                if (tpIndex != -1)
                {
                    
                    int checkNum = ItemList[tpIndex].ItemNum;
                    Boolean singleF = checkNum % 2 == 1;
                    if (singleF)
                    {
                        warnInfo.warnF = false;
                        string tempTig = "面板螺丝数量不为单数请核对!";
                        Sursb.AppendLine(tempTig);
                    }
                    else
                    {
                        SurF = checkNum < bigSNum;
                        if (SurF)
                        {
                            warnInfo.warnF = false;
                            string tempTig = "面板螺丝数量少于标准(" + bigSNum + "个)请核对!";
                            Sursb.AppendLine(tempTig);
                        }
                    }
                }

                int kIndex = ItemList.FindIndex(item => item.ItemName.Equals("公制螺丝"));
                if (kIndex != -1)
                {
                    int checkNum = ItemList[kIndex].ItemNum;
                    Boolean singleF = checkNum % 2 == 1;
                    if (singleF)
                    {
                        warnInfo.warnF = false;
                        string tempTig = "公制螺丝数量不为单数请核对!";
                        Sursb.AppendLine(tempTig);
                    }
                    else
                    {
                        SurF = checkNum < bigSNum;
                        if (SurF)
                        {
                            warnInfo.warnF = false;
                            string tempTig = "公制螺丝数量少于标准(" + bigSNum + "个)请核对!";
                            Sursb.AppendLine(tempTig);
                        }
                    }

                }

                int fIndex = ItemList.FindIndex(item => item.ItemName.Equals("方铁螺丝"));
                if (fIndex != -1)
                {
                    int checkNum = ItemList[fIndex].ItemNum;
                    Boolean singleF = checkNum % 2 == 1;
                    if (singleF)
                    {
                        warnInfo.warnF = false;
                        string tempTig = "方铁螺丝数量不为单数请核对!";
                        Sursb.AppendLine(tempTig);
                    }
                    else
                    {
                        SurF = checkNum < bigSNum;
                        if (SurF)
                        {
                            warnInfo.warnF = false;
                            string tempTig = "方铁螺丝数量少于标准(" + bigSNum + "个)请核对!";
                            Sursb.AppendLine(tempTig);
                        }
                    }
                }

                int bpIndex = ItemList.FindIndex(item => item.ItemName.Equals("底板螺丝"));
                if (bpIndex != -1)
                {
                    int checkNum = ItemList[bpIndex].ItemNum;
                    Boolean singleF = checkNum % 2 == 1;
                    SurF = checkNum < smallSNum;
                    if (singleF)
                    {
                        warnInfo.warnF = false;
                        string tempTig = "底板螺丝数量不为单数请核对!";
                        Sursb.AppendLine(tempTig);
                    }
                    else
                    {
                        if (SurF)
                        {
                            warnInfo.warnF = false;
                            string tempTig = "底板螺丝数量少于标准(" + smallSNum + "个)请核对!";
                            Sursb.AppendLine(tempTig);
                        }
                    }
                }

                int epfpIndex = ItemList.FindIndex(item => item.ItemName.Equals("针板螺丝"));
                if (epfpIndex != -1)
                {
                    int checkNum = ItemList[epfpIndex].ItemNum;
                    Boolean singleF = checkNum % 2 == 1;
                    SurF = checkNum < epfpSNum;
                    if (singleF)
                    {
                        warnInfo.warnF = false;
                        string tempTig = "针板螺丝数量不为单数请核对!";
                        Sursb.AppendLine(tempTig);
                    }
                    else
                    {
                        if (SurF)
                        {
                            warnInfo.warnF = false;
                            string tempTig = "针板螺丝数量少于标准(" + epfpSNum + "个)请核对!";
                            Sursb.AppendLine(tempTig);
                        }
                    }
                }

            }
            warnInfo.tig = Sursb.ToString();
            return warnInfo;
        }

        //FoolProofing Check
        public AMTypeCheckWarn ATypeFoolProofingCheck()
        {
            AMTypeCheckWarn Res = new AMTypeCheckWarn();
            AMTypeCheckWarn rItemCheck = ATypeRItemWithDBFoolPro();
            AMTypeCheckWarn surItemCheck = ATypeSurItemWithDBFoolPro();
            Boolean surItemNoF = !surItemCheck.warnF;
            Boolean rItemNoF = !rItemCheck.warnF;
            StringBuilder sb = new StringBuilder();
            if (rItemNoF)
            {
                sb.AppendLine("识别零件表格: ");
                sb.AppendLine(rItemCheck.tig);
            }
            if (surItemNoF)
            {
                sb.AppendLine("补充零件表格: ");
                sb.AppendLine(surItemCheck.tig);
            }
            
            if(surItemNoF || rItemNoF)
            {
                Res.warnF = false;
                Res.tig = sb.ToString();
            }
            return Res;
        }

        public void ATypeSendERPDataEvent(string UploadUser,Boolean tempSaveF)
        {
            ComputedUtils.GetStandardItemSpe();
            Boolean F1 = ATypeCheckBasicInfoFill(tempSaveF);
            if (F1)
            {
                if (!tempSaveF)
                {
                    AMTypeCheckWarn warnInfo = ATypeFoolProofingCheck();;
                    if (warnInfo.warnF)
                         ATypeSendDataToDbAndERP(UploadUser,false);
                    else
                    {
                        warnInfo.tig += "是否继续上传?";
                        DialogResult result = MessageBox.Show(warnInfo.tig,
                                              "请注意",
                                              MessageBoxButtons.YesNo,
                                              MessageBoxIcon.Question);

                        if (result == DialogResult.Yes)
                            ATypeSendDataToDbAndERP(UploadUser, false);
                        if (result == DialogResult.No)
                            return;
                    }
                }
                else
                     ATypeSendDataToDbAndERP(UploadUser, tempSaveF);
            }
        }

        //上传前 校验基本数据
        public Boolean ATypeCheckBasicInfoFill(Boolean tempSaveF)
        {
            if (!tempSaveF)
            {
                string Account = (string)RecognizeUtils.dataForm.ULForm.UserAccountText.Texts;
                string Customer = RecognizeUtils.CustomerNum;
                if (Customer == null)
                {
                    MessageBox.Show("请选择客户!");
                    return false;
                }
                if (Account == null)
                {
                    MessageBox.Show("请先设置账户信息!");
                    return false;
                }
                if (Account.Trim().Equals(""))
                {
                    MessageBox.Show("请先设置账户信息!");
                    return false;
                }
                if (AssemblyShareData.ASectionList.Count == 0)
                {
                    MessageBox.Show("未识别出板件数据 无法上传ERP!");
                    return false;
                }
            }
            return true;
        }

        //上传前 校验基本数据
        public static Boolean CheckInfoBeforeUploadRule(Boolean tempSaveF = false)
        {
            if (!tempSaveF)
            {
                string Customer = RecognizeUtils.CustomerNum;
                if (Customer == null)
                {
                    MessageBox.Show("请选择客户!");
                    return false;
                }
            }
            return true;
        }

        //请求报价单号
        public static async Task<string> AskQuaNumber(string quafileName,string mesOrder)
        {
            string erpOrderCode = "";
            try
            {
                HttpClient UserClient = new HttpClient();
                string query = FILESYSURL + FILESYSQuaURL + "/" + mesOrder;
                UserClient.Timeout = TimeSpan.FromSeconds(1000);
                var response = await UserClient.GetAsync(query);
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    var jsonResponse = await response.Content.ReadAsStringAsync();
                    JObject jsonParseObj = JObject.Parse(jsonResponse);
                    if (jsonParseObj["code"].ToString().Equals("200"))
                    {
                        var dataObj = jsonParseObj["data"];
                        if(dataObj != null)
                        {
                            JObject dataObjData = JObject.Parse(dataObj.ToString());
                            JArray quaArray = (JArray)dataObjData["ctQaotationFileList"];
                            foreach (JObject item in quaArray)  
                            {
                                string fileId = item["fileId"].ToString();
                                string fileName = item["fileName"].ToString();
                                bool F = fileName.Equals(quafileName);
                                if(F)
                                    erpOrderCode = mesOrder + "_" + fileId;
                            }
                        }
                    }
                    else
                        MessageBox.Show("文档管理系统处理失败!");
                }
                else
                    MessageBox.Show("请求文档管理系统失败!");
            }
            catch (Exception e)
            {

            }
            return erpOrderCode;
        }

        //文档系统 查询孔距
        public static async Task<List<GarbageSysResDataItem>> AskFileSysHoleData(GarbageSysHolePosData infoData)
        {
            List<GarbageSysResDataItem> Res = new List<GarbageSysResDataItem>();
            try
            {
                HttpClient UserClient = new HttpClient();
                UserClient.BaseAddress = new Uri(FILESYSURL);
                UserClient.Timeout = TimeSpan.FromSeconds(1000);
                var jsonContent = JsonConvert.SerializeObject(infoData);
                var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
                var response = await UserClient.PostAsync(FILESYSHoleURL, content);
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    var jsonResponse = await response.Content.ReadAsStringAsync();
                    JObject jsonParseObj = JObject.Parse(jsonResponse);
                    if (jsonParseObj["code"].ToString().Equals("200"))
                    {
                        JArray dataArray = JArray.Parse(jsonParseObj["data"].ToString());
                        if(dataArray.Count> 0)
                        {
                            foreach(JObject item in dataArray)
                            {
                                GarbageSysResDataItem temp = new GarbageSysResDataItem();
                                temp.partUid = Convert.ToString(item["partUid"]);
                                temp.moldPart = Convert.ToString(item["moldPart"]);
                                temp.distanceLength = Convert.ToInt32(item["distanceLength"]);
                                temp.distanceWidth = Convert.ToInt32(item["distanceWidth"]);
                                temp.moldPart = Convert.ToString(item["moldPart"]);
                                temp.partDiam = Convert.ToInt32(item["partDiam"]);
                                temp.holeNum = Convert.ToInt32(item["holeNum"]);
                                temp.standardFlag = Convert.ToBoolean(item["standardFlag"]);
                                List<CAD_Point> points = new List<CAD_Point>();
                                JArray pointsArray = JArray.Parse(item["points"].ToString());
                                if(pointsArray.Count > 0)
                                {
                                    foreach(JObject holeItem in pointsArray)
                                    {
                                        CAD_Point pointItem = new CAD_Point();
                                        pointItem.X = Convert.ToDouble(holeItem["x"]);
                                        pointItem.Y = Convert.ToDouble(holeItem["y"]);
                                        points.Add(pointItem);
                                    }
                                }
                                temp.points = points;
                                Res.Add(temp);
                            }
                        }
                    }
                    else
                        MessageBox.Show("文档管理系统处理失败!");
                }
                else
                    MessageBox.Show("请求文档管理系统失败!");
            }
            catch (Exception e)
            {
                MessageBox.Show("数据处理异常");
            }
            return Res;
        }

        //自动模式 对接ERP 上传模架加工数据 tempSaveF 临时保存标识
        public async void ATypeSendDataToDbAndERP(string UploadUser,Boolean tempSaveF)
        {
            string quaOrderNum = "";
            DwgFileInfo fInfo = CADAuxiliaryUtils.GetCurrentDrawingPath();
            string complePath = fInfo.complePath;
            string[] pathSplitArray = complePath.Split('\\');
            ConvertUtils CU = new ConvertUtils();
            string JobNumber = (string)RecognizeUtils.dataForm.ULForm.UserAccountText.Texts;
            string JobNumberName = (string)RecognizeUtils.dataForm.ULForm.UserNameText.Texts;
            string Fancy = (string)RecognizeUtils.dataForm.FancySelectBox.SelectedItem;
            string ModeNum = RecognizeUtils.dataForm.ModeNumText.Texts;
            var uploadtime = DateTime.Now;
            string tempOrder = "R2D" + uploadtime.ToString("yymmddHHmmss") + "A";
            //Trans -> BaseInfo
            string ModeSize = null;
            string MidthStr = MoldBaseShare.Width.ToString();
            string LengthStr = MoldBaseShare.Length.ToString();
            if(MidthStr.Length >= 2 && LengthStr.Length >= 2)
                ModeSize = MidthStr.Substring(0, 2) + LengthStr.Substring(0, 2);
            ModeBasicData BasicData = new ModeBasicData();
            BasicData.Customer = RecognizeUtils.CustomerNum;
            BasicData.BatchNum = (string)RecognizeUtils.dataForm.BatchNumBox.Texts;
            BasicData.FancyType = Fancy;
            BasicData.ModeNum = ModeNum;
            BasicData.ModeSize = ModeSize;
            BasicData.JobNumber = JobNumber;
            BasicData.tempOrderNumber = tempOrder;
            //Process Data Includes DB Process Data
            ProcessData PostData = CU.ATypeTransToPHoleAndERPData(BasicData);
            
            //Save Process -> DB
            ATypeSaveProcessHoleToDB(tempOrder, UploadUser, uploadtime, PostData.HoleProcessData);
            
            PostData.HoleProcessData = null;
            //Serialize Data
            var jsonContent = JsonConvert.SerializeObject(PostData);

            AMTypeUPloadRecordInfo RInfo = ConvertUtils.AutoTypeTransToRecordInfo(PostData);
            RInfo.jobNumberName = JobNumberName;
            RInfo.UID = tempOrder;
            RInfo.batchNum = fInfo.batchNum;
            RInfo.dwgfilePath = fInfo.complePath;
            RInfo.dwgfileName = fInfo.dwgName;
            RInfo.uploadTime = uploadtime;

            if (tempSaveF)
                RInfo.uploadType = 3;
            else
                RInfo.uploadType = 1;
            if (tempSaveF)
                Mould.SaveUploadRecordToDB(RInfo, RInfo.jobNumberName);
            else
                ERPPartyReqEvent(jsonContent, CU, RInfo);

        }

        public  async Task SendDataToDbAndERP(MTypeAllCheckBoxVInfo BVInfo,ProcessData PostData,Boolean tempSaveF)
        {
            ConvertUtils CU = new ConvertUtils();
            AMTypeUPloadRecordInfo RInfo = new AMTypeUPloadRecordInfo();
            DwgFileInfo fInfo = CADAuxiliaryUtils.GetCurrentDrawingPath();
            string JobNumberName = (string)RecognizeUtils.dataForm.ULForm.UserNameText.Texts;
            RInfo.jobNumberName = JobNumberName;
            RInfo.UID = PostData.BasicData.tempOrderNumber;
            RInfo.batchNum = PostData.BasicData.BatchNum;
            RInfo.dwgfilePath = fInfo.complePath;
            RInfo.dwgfileName = fInfo.dwgName;
            RInfo.uploadTime  = DateTime.Now;
            RInfo.modeSize = PostData.BasicData.ModeSize;
            if (tempSaveF)
                RInfo.uploadType = 4;
            else
                RInfo.uploadType = 2;
            var jsonContent = JsonConvert.SerializeObject(PostData);
            RInfo.quoInfo = MTypeSerializationOriginData(BVInfo);
            if(tempSaveF)
                Mould.SaveUploadRecordToDB(RInfo, RInfo.jobNumberName);
            else
                ERPPartyReqEvent(jsonContent, CU, RInfo);
        }

    }

   
}
